package com.gestocasa.view.dialogs.helper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.swing.JTextField;

import com.gestocasa.model.Attribute;

public class JAttributeTextField extends JTextField {

	private Attribute attribute;
	private boolean allowEmptyValues;
	
	public JAttributeTextField(Attribute a) {
		super();
		attribute = a;
		allowEmptyValues = false;
	}
	
	public Attribute getAttribute() {
		return attribute;
	}

	public void setAttribute(Attribute attribute) {
		this.attribute = attribute;
	}

	public void setAllowEmptyValues(boolean allowEmptyValues) {
		this.allowEmptyValues = allowEmptyValues;
	}
	
	public boolean isAllowEmptyValues() {
		return allowEmptyValues;
	}
	
	public boolean isValidated() {
		boolean valid = true;
		String text = getText();
		
		if(attribute != null) {
			if(allowEmptyValues == false || text.isEmpty() == false) {
				if(Attribute.TYPE_DATE.equals(attribute.getType())) {
					SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
					try {
						sdf.parse(text);
					} catch (ParseException e) {
						valid = false;
					}
				}
				else if(Attribute.TYPE_NUMBER.equals(attribute.getType())) {
					try {
						Double.parseDouble(text.replace(",", "."));
					}
					catch(NumberFormatException e) {
						valid = false;
					}
					catch(NullPointerException e) {
						valid = false;
					}
				}
			}
		}
		return valid;
	}
	
	public Object getValue() {
		Object obj = null;
		String text = getText();
		
		if(attribute != null) {
			if(Attribute.TYPE_DATE.equals(attribute.getType())) {
				// Formato aceptado dd/mm/YYYY
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
				try {
					obj = sdf.parse(text);
				} catch (ParseException e) {
					obj = null;
				}
			}
			else if(Attribute.TYPE_NUMBER.equals(attribute.getType())) {
				try {
					obj = Double.parseDouble(text.replace(",", "."));
				}
				catch(NumberFormatException e) {
					obj = null;
				}
				catch(NullPointerException e) {
					obj = null;
				}
			}
			else if(Attribute.TYPE_STRING.equals(attribute.getType())) {
				obj = text;
			}
		}
		
		return obj;
	}
	
	public static void main(String args[]) {
		String tDate = "10/09/2012";
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		System.out.println(tDate);
		try {
			System.out.println(sdf.parse(tDate));
		} catch (ParseException e) {
			System.out.println("Ups! Error al parsear fecha...");
		}
	}
}
